import logging
import time
from typing import Optional, Dict, Any, Tuple

from werkzeug.datastructures.mixins import F
from .models import CmUserFrequency, CmUserVip, CmUserOrder, CmUserProduct
from .cm_user import CmUser
from init import db

# 获取日志记录器
logger = logging.getLogger(__name__)

class VipService:
    """
    会员管理服务
    负责用户次数管理、VIP等级管理、订单管理等
    """
    
    def __init__(self):
        self.ds = db.session
    
    def get_user_frequency(self, user_id: int) -> Optional[CmUserFrequency]:
        """
        获取用户次数信息
        """
        try:
            frequency = self.ds.query(CmUserFrequency).filter(
                CmUserFrequency.user_id == user_id
            ).first()
            
            if not frequency:
                # 如果用户没有次数记录，创建一个默认记录
                frequency = CmUserFrequency(
                    user_id=user_id,
                    free_frequency=0,
                    restricted_frequency=0,
                    permanent_frequency=0
                )
                self.ds.add(frequency)
                self.ds.commit()
                self.ds.refresh(frequency)
                logger.info(f"为用户 {user_id} 创建默认次数记录")
            
            return frequency
        except Exception as e:
            logger.error(f"获取用户 {user_id} 次数信息失败: {str(e)}")
            self.ds.rollback()
            return None
    
    def consume_frequency(self, user_id: int, consume_count: int = 1) -> Tuple[bool, str]:
        """
        消费用户次数
        按照受限次数->免费次数->永久次数的顺序扣除
        
        Args:
            user_id: 用户ID
            consume_count: 消费次数，默认1次
            
        Returns:
            (success, message): 是否成功，消息
        """
        try:
            frequency = self.get_user_frequency(user_id)
            if not frequency:
                return False, "获取用户次数信息失败"
            
            logger.info(f"用户 {user_id} 开始消费次数，当前次数: 受限={frequency.restricted_frequency}, 免费={frequency.free_frequency}, 永久={frequency.permanent_frequency}")
            
            # 计算总可用次数
            total_available = frequency.restricted_frequency + frequency.free_frequency + frequency.permanent_frequency
            
            if total_available < consume_count:
                return False, f"次数不足，需要 {consume_count} 次，可用 {total_available} 次"
            
            # 按照优先级顺序扣除次数
            remaining_consume = consume_count
            
            # 1. 先扣除受限次数
            if frequency.restricted_frequency > 0 and remaining_consume > 0:
                consume_from_restricted = min(frequency.restricted_frequency, remaining_consume)
                frequency.restricted_frequency -= consume_from_restricted
                remaining_consume -= consume_from_restricted
                logger.info(f"用户 {user_id} 扣除受限次数 {consume_from_restricted}")
            
            # 2. 再扣除免费次数
            if frequency.free_frequency > 0 and remaining_consume > 0:
                consume_from_free = min(frequency.free_frequency, remaining_consume)
                frequency.free_frequency -= consume_from_free
                remaining_consume -= consume_from_free
                logger.info(f"用户 {user_id} 扣除免费次数 {consume_from_free}")
            
            # 3. 最后扣除永久次数
            if frequency.permanent_frequency > 0 and remaining_consume > 0:
                consume_from_permanent = min(frequency.permanent_frequency, remaining_consume)
                frequency.permanent_frequency -= consume_from_permanent
                remaining_consume -= consume_from_permanent
                logger.info(f"用户 {user_id} 扣除永久次数 {consume_from_permanent}")
            
            self.ds.commit()
            
            logger.info(f"用户 {user_id} 成功消费 {consume_count} 次，剩余次数: 受限={frequency.restricted_frequency}, 免费={frequency.free_frequency}, 永久={frequency.permanent_frequency}")
            
            return True, f"成功消费 {consume_count} 次"
            
        except Exception as e:
            logger.error(f"用户 {user_id} 消费次数失败: {str(e)}")
            self.ds.rollback()
            return False, f"消费次数失败: {str(e)}"
    
    def add_frequency(self, user_id: int, frequency_type: str, count: int) -> Tuple[bool, str]:
        """
        为用户添加次数
        
        Args:
            user_id: 用户ID
            frequency_type: 次数类型 ('restricted', 'free', 'permanent')
            count: 添加次数
            
        Returns:
            (success, message): 是否成功，消息
        """
        try:
            frequency = self.get_user_frequency(user_id)
            if not frequency:
                return False, "获取用户次数信息失败"
            
            if frequency_type == 'restricted':
                frequency.restricted_frequency += count
                logger.info(f"为用户 {user_id} 添加受限次数 {count}")
            elif frequency_type == 'free':
                frequency.free_frequency += count
                logger.info(f"为用户 {user_id} 添加免费次数 {count}")
            elif frequency_type == 'permanent':
                frequency.permanent_frequency += count
                logger.info(f"为用户 {user_id} 添加永久次数 {count}")
            else:
                return False, f"无效的次数类型: {frequency_type}"
            
            self.ds.commit()
            return True, f"成功添加 {count} 次 {frequency_type} 次数"
            
        except Exception as e:
            logger.error(f"为用户 {user_id} 添加次数失败: {str(e)}")
            self.ds.rollback()
            return False, f"添加次数失败: {str(e)}"
    
    def get_user_vip_info(self, user_id: int) -> Optional[Dict[str, Any]]:
        """
        获取用户VIP信息
        """
        try:
            vip = self.ds.query(CmUserVip).filter(
                CmUserVip.user_id == user_id
            ).first()
            
            if not vip:
                return None
            
            current_time = int(time.time())
            is_expired = current_time > vip.expire_at
            
            return {
                'user_id': vip.user_id,
                'vip_level': vip.vip_level,
                'start_at': vip.start_at,
                'expire_at': vip.expire_at,
                'is_expired': is_expired,
                'remaining_days': max(0, (vip.expire_at - current_time) // 86400) if not is_expired else 0
            }
        except Exception as e:
            logger.error(f"获取用户 {user_id} VIP信息失败: {str(e)}")
            return None
    
    def create_vip(self, user_id: int, free_times: int, duration_days: int) -> Tuple[bool, str]:
        """
        创建或更新用户VIP
        
        Args:
            user_id: 用户ID
            free_times: 免费次数
            duration_days: VIP有效期（天）
            
        Returns:
            (success, message): 是否成功，消息
        """
        try:
            current_time = int(time.time())
            expire_time = current_time + (duration_days * 86400)
            
            # 查找现有VIP记录
            vip = self.ds.query(CmUserVip).filter(
                CmUserVip.user_id == user_id
            ).first()
            
            if vip:
                # 更新现有VIP
                vip.free_times = free_times
                vip.expire_at = expire_time
                logger.info(f"更新用户 {user_id} VIP，免费次数: {free_times}，有效期: {duration_days}天")
            else:
                # 创建新VIP
                vip = CmUserVip(
                    user_id=user_id,
                    free_times=free_times,
                    start_at=current_time,
                    expire_at=expire_time
                )
                self.ds.add(vip)
                logger.info(f"为用户 {user_id} 创建VIP，免费次数: {free_times}，有效期: {duration_days}天")
            
            self.ds.commit()
            return True, f"VIP创建成功，免费次数: {free_times}，有效期: {duration_days}天"
            
        except Exception as e:
            logger.error(f"为用户 {user_id} 创建VIP失败: {str(e)}")
            self.ds.rollback()
            return False, f"创建VIP失败: {str(e)}"
    
    def check_user_permission(self, user_frequency: CmUserFrequency, vip_info: Dict[str, Any]) -> Tuple[bool, int]:
        """
        检查用户是否有权限执行任务
        
        Returns:
            (has_permission, message): 是否有权限，消息
        """
        try:
            # 获取用户次数信息
            
            if not user_frequency:
                return False, "获取用户次数信息失败"
            
            # 检查VIP状态
            if not vip_info:
                user_frequency.restricted_frequency = 0
            
            total_available = user_frequency.restricted_frequency + user_frequency.free_frequency + user_frequency.permanent_frequency
            
            if total_available > 0:
                return True, total_available
            
            
            
            return False, 0
            
        except Exception as e:
            logger.error(f"检查用户 {user_id} 权限失败: {str(e)}")
            return False, 0
    
    def get_user_summary(self, user_id: int) -> Dict[str, Any]:
        """
        获取用户完整信息摘要
        """
        try:
            frequency = self.get_user_frequency(user_id)
            vip_info = self.get_user_vip_info(user_id)
            
            summary = {
                'user_id': user_id,
                'frequency': {
                    'restricted': frequency.restricted_frequency if frequency else 0,
                    'free': frequency.free_frequency if frequency else 0,
                    'permanent': frequency.permanent_frequency if frequency else 0,
                    'total': (frequency.restricted_frequency + frequency.free_frequency + frequency.permanent_frequency) if frequency else 0
                },
                'vip': vip_info,
                'can_use': False
            }
            
            # 检查是否有可用次数
            summary['can_use'] = summary['frequency']['total'] > 0
            
            return summary
            
        except Exception as e:
            logger.error(f"获取用户 {user_id} 摘要失败: {str(e)}")
            return {
                'user_id': user_id,
                'frequency': {'restricted': 0, 'free': 0, 'permanent': 0, 'total': 0},
                'vip': None,
                'can_use': False,
                'message': f"获取用户信息失败: {str(e)}"
            }

# 创建全局实例
vip_service = VipService()
